import java.awt.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Map;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.SliderUI;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import com.mysql.jdbc.Connection;

/*
 * SliderDemo.java requires all the files in the images/doggy
 * directory.
 */
/**
 * @author Djura
 *
 */
public class TimeSlider extends JPanel
implements ActionListener,
WindowListener,
ChangeListener {
	//Set up animation parameters.
	static final int FPS_MIN = 0;
	static final int FPS_MAX = 30;
	static final int FPS_INIT = 15;    //initial frames per second
	static final long DAY_MILLIS = 604800000L;
	int frameNumber = 0;
	int NUM_FRAMES = 14;
	ImageIcon[] images = new ImageIcon[NUM_FRAMES];
	int delay;
	Timer timer;
	boolean frozen = false;
	long maxWeekTime;
	int beginWeek;
	int endWeek;
	Framework fw;

	java.sql.Connection connection;

	public TimeSlider(Framework fw) {
		this.fw = fw;
		databaseConnect();
		Map<String, Long> weeks = getWeeks();
		endWeek = ((Long)weeks.get("end_week")).intValue();
		beginWeek = ((Long)weeks.get("begin_week")).intValue();
		maxWeekTime = (Long)weeks.get("max_time");
		System.out.println("beginWeekNr: " + beginWeek + " endWeeknr: " + endWeek);

		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		
		setBackground(Color.WHITE);


		//Create the label.
		JLabel sliderLabel = new JLabel("Week", JLabel.CENTER);
		sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
		
		//Create the slider.
		JSlider week = new JSlider(JSlider.HORIZONTAL,
				beginWeek, endWeek, endWeek);
		week.setBackground(Color.WHITE);
		week.setForeground(Color.BLACK);

		week.addChangeListener(this);

		//Turn on labels at major tick marks.
		week.setSnapToTicks(true);
		week.setMajorTickSpacing(1);
		week.setPaintTicks(true);
		week.setPaintLabels(true);
		week.setBorder(
				BorderFactory.createEmptyBorder(0,0,10,0));
		Font font = new Font("Serif", Font.ITALIC, 15);
		week.setFont(font);

		//Put everything together.
		add(sliderLabel);
		add(week);
		setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
		this.setBackground(Color.WHITE);

	}

	private void databaseConnect() {
		connection = null;
		try {
			// Load the JDBC driver
			String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
			Class.forName(driverName);

			// Create a connection to the database
			//String serverName = "djura.crabdance.com";
			String serverName = "localhost";
			String mydatabase = "infviz";
			String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
			String username = "root";
			String password = "augmented";
			connection = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			// Could not find the database driver
		} catch (SQLException e) {
			// Could not connect to the database
		} 

	}

	private Map<String, Long> getWeeks(){
		String sql = "SELECT WEEK(MIN(created_date)) as begin_week, WEEK(MAX(created_date)) as end_week, UNIX_TIMESTAMP(MAX(created_date)) * 1000 as max_time FROM tweet";
		QueryRunner qr = new QueryRunner();
		ResultSetHandler rsh = new MapHandler();
		Map<String, Long> result = null;
		try {
			result = (Map<String, Long>) qr.query(connection, sql, rsh);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;

	}


	/** Add a listener for window events. */
	void addWindowListener(Window w) {
		w.addWindowListener(this);
	}

	public void windowOpened(WindowEvent e) {}
	public void windowClosing(WindowEvent e) {}
	public void windowClosed(WindowEvent e) {}
	public void windowActivated(WindowEvent e) {}
	public void windowDeactivated(WindowEvent e) {}

	/** Listen to the slider. */
	public void stateChanged(ChangeEvent e) {
		JSlider source = (JSlider)e.getSource();
		if (!source.getValueIsAdjusting()) {
			int week = (int)source.getValue();
			int weekDiff = endWeek - week;
			long startMillis = maxWeekTime - weekDiff * DAY_MILLIS;
			long endMillis = startMillis + 7 * DAY_MILLIS;

			Timestamp startTime = new Timestamp(startMillis);
			Timestamp endTime = new Timestamp(endMillis);
			
			System.out.println("New start: " + startTime + " new end: " + endTime);
			
			fw.setTimeSpan(startTime, endTime);

		}
	}

	//Called when the Timer fires.
	public void actionPerformed(ActionEvent e) {
		
	}


	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createImageIcon(String path) {
		java.net.URL imgURL = TimeSlider.class.getResource(path);
		if (imgURL != null) {
			return new ImageIcon(imgURL);
		} else {
			System.err.println("Couldn't find file: " + path);
			return null;
		}
	}

	/**
	 * Create the GUI and show it.  For thread safety,
	 * this method should be invoked from the
	 * event-dispatching thread.
	 */
	private static void createAndShowGUI() {
		//Create and set up the window.
		JFrame frame = new JFrame("SliderDemo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		TimeSlider animator = new TimeSlider(null);

		//Add content to the window.
		frame.add(animator, BorderLayout.CENTER);

		//Display the window.
		frame.pack();
		frame.setVisible(true); 
	}

	public static void main(String[] args) {
		/* Turn off metal's use of bold fonts */
		UIManager.put("swing.boldMetal", Boolean.FALSE);


		//Schedule a job for the event-dispatching thread:
		//creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}

